# -*- coding: utf-8 -*-
import copy
import random
import scrapy
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from datetime import datetime
from zc_core.dao.batch_dao import BatchDao
from zc_core.dao.sku_dao import SkuDao
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from plap_deli.rules import parse_item_data
from plap_deli.utils.done_filter import DoneFilter
from plap_deli.utils.login import SeleniumLogin
from zc_core.spiders.base import BaseSpider


class DeliDetailSpider(BaseSpider):
    name = 'deli_detail'
    custom_settings = {
        'CONCURRENT_REQUESTS': 8,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 8,
        'CONCURRENT_REQUESTS_PER_IP': 8,
    }
    # 常用链接
    item_url = 'http://mall.plap.cn/products/{}'

    def __init__(self, batchNo=None, delta_hour=-12, *args, **kwargs):
        super(DeliDetailSpider, self).__init__(batchNo=batchNo, hourOffset=delta_hour, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        settings = get_project_settings()
        cookies = SeleniumLogin().get_cookies('data')
        # cookies = {'_session_id': '305d2d2b2d40c263bfd42bf7d60db5e1'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        # pool_list = SkuDao().get_batch_sku_list(batch_no=self.batch_no, fields=None)
        pool_list = SkuPoolDao().get_sku_pool_list(fields=None)
        self.logger.info('全量：%s' % (len(pool_list)))
        dist_list = [x for x in pool_list if not self.done_filter.contains(x.get('_id'))]
        self.logger.info('目标：%s' % (len(dist_list)))
        random.shuffle(dist_list)
        for sku in dist_list:
            sku_id = sku.get('_id')
            # 避免无效采集
            offline_time = sku.pop('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue

            # 采集商品价格及状态
            yield Request(
                url=self.item_url.format(sku_id),
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'sku': copy.copy(sku),
                },
                cookies=cookies,
                callback=self.parse_item_data,
                errback=self.error_back,
                priority=25,
            )

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')

        data = parse_item_data(response)
        if data:
            self.logger.info('商品: [%s]' % sku_id)
            yield data
        else:
            self.logger.error('下架: [%s]' % sku_id)
